//
//  StringExtension.swift
//  DragonWallet
//
//  Created by volantPig on 2024/2/28.
//

import UIKit
import CommonCrypto

class StringExtension: NSObject {

}

extension String {
    func strMD5() -> String {
        let data = (self as NSString).data(using: String.Encoding.utf8.rawValue)! as NSData
        return data.MD5().hexedString()
    }
    
    /// Find the location of all substring
    /// - Parameter string: substring
    func findAllIndex(_ string: String) -> [NSRange] {
        var ranges: [NSRange] = []
        if string.elementsEqual("") {
            return ranges
        }
        let zero = self.startIndex
        let target = Array(string)
        let total = Array(self)
        let lenght = string.count
        var startPoint = 0
        while total.count >= startPoint + string.count {
            if total[startPoint] == target[0] {
                let startIndex = self.index(zero, offsetBy: startPoint)
                let endIndex = self.index(startIndex, offsetBy: lenght)
                let child = self[startIndex..<endIndex]
                if child.elementsEqual(string) {
                    ranges.append(NSRange.init(location: startPoint, length: lenght))
                    startPoint += lenght
                } else {
                    startPoint += 1
                }
            } else {
                startPoint += 1
            }
        }
        return ranges
    }
    
    /// 验证校验邮箱
    func isValidEmail() -> Bool {
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailTest.evaluate(with: self)
    }
    
    /// 正则校验国际版手机号
    func isGlobalValidNumber() -> Bool {
        let pattern = "^\\d{5,20}$"
        let predicate = NSPredicate(format: "SELF MATCHES %@", pattern)
        return predicate.evaluate(with: self)
    }
    
    /// 电话号码校验
    func verificationMobile() -> Bool {
        let regex: String = "^1\\d{10}$"
        let test = NSPredicate(format: "SELF MATCHES %@", regex)
        return test.evaluate(with: self)
    }
    
    func hidePhoneNumber() -> String {  
        if self.count < 5 {
            var str = ""
            for _ in 0 ..< self.count {
                str += "*"
            }
            return str
        } else {
            //替换一段内容，两个参数：替换的范围和用来替换的内容
            let start = self.index(self.startIndex, offsetBy: (self.count - 5) / 2)
            let end = self.index(self.startIndex, offsetBy: (self.count - 5) / 2 + 4)
            let range = Range(uncheckedBounds: (lower: start, upper: end))
            return self.replacingCharacters(in: range, with: "****")
        }
    }
    
    /// 追加图片
    func appendImgV(_ imageInfo: Any,at index: Int = -1) -> NSAttributedString {
        
        var image: UIImage?
        if type(of: imageInfo).self == String.self {
            print("文字")
            let imageName = imageInfo as! String
            image = UIImage.init(named: imageName)
        }
        
        if type(of: imageInfo).self == UIImage.self {
            print("图片")
            image = imageInfo as? UIImage
        }
        
        if type(of: imageInfo).self == UIImageView.self {
            print("imageView")
            let imgV = imageInfo as! UIImageView
            image = imgV.image
        }

        let attach = NSTextAttachment()
        attach.image = image
        
        let imageStr = NSAttributedString.init(attachment: attach)
        let attributeStr = NSMutableAttributedString.init(string: self)
        
        if index == -1 {
            attributeStr.append(imageStr)
        } else {
            attributeStr.insert(imageStr, at: index)
        }
        return attributeStr
    }
    
}
